/* eslint-disable @typescript-eslint/no-non-null-assertion */

import { requestClient } from '#/api/request';

// 将data数据转换为树形结构，把parentId作为父节点的id，id为machineryTypeId字段，将有parentId的节点作为子节点放进对应machineryTypeId的children数组中
export function convertToTree<T extends Record<string, any>>(
  data: T[],
  idP: string,
  pid: string,
): T[] {
  if (!data || data.length === 0) return [];

  const tree: T[] = [];
  const map: Record<string, T & { children: T[] }> = {};

  // 首先创建所有节点的映射
  data.forEach((item) => {
    if (item[idP] !== undefined) {
      map[item[idP]] = { ...item, children: [] };
    }
  });

  // 构建树形结构
  data.forEach((item) => {
    if (item[pid] !== undefined && item[idP] !== undefined) {
      const parent = map[item[pid]];
      if (parent) {
        parent.children.push(map[item[idP]]!);
      } else {
        tree.push(map[item[idP]]!);
      }
    }
  });

  return tree;
}

export namespace DVMTAPI {
  export enum EnableFlag {
    N = 'N',
    Y = 'Y',
  }

  export type Params = object;
  export interface Datum {
    searchValue: null;
    createBy: string;
    createTime: Date;
    updateBy: string;
    updateTime: Date | null;
    remark: string;
    params: Params;
    parentName: null;
    parentId: null;
    orderNum: null;
    ancestors: string;
    children: any[];
    machineryTypeId: number;
    machineryTypeCode: string;
    machineryTypeName: string;
    parentTypeId: number;
    enableFlag: EnableFlag;
    attr1: null | string;
    attr2: null;
    attr3: number;
    attr4: number;
  }
  export interface MachinerytypeListResp {
    msg: string;
    code: number;
    data: Datum[];
  }
}
// 获取类型列表
export const getMachinerytypeList = async (params: any) => {
  const res = await requestClient.get<DVMTAPI.MachinerytypeListResp>(
    '/mes/dv/machinerytype/list',
    { params },
  );
  // res.data = convertToTree(res.data, 'machineryTypeId', 'parentTypeId');
  return res;
};

/**
 *
 * @returns 获取处理后的类型列表
 */
export const getMachineryTypeHandleList = async () => {
  const res = await requestClient.get<DVMTAPI.MachinerytypeListResp>(
    '/mes/dv/machinerytype/list',
  );
  return convertToTree(res.data, 'machineryTypeId', 'parentTypeId');
};

// 修改类型设置
export const updateMachineryTypeMenu = (data: DVMTAPI.Datum) =>
  requestClient.put<DVMTAPI.MachinerytypeListResp>(
    '/mes/dv/machinerytype',
    data,
  );

// 增加类型设置
export const addMachineryTypeMenu = (data: DVMTAPI.Datum) =>
  requestClient.post<DVMTAPI.MachinerytypeListResp>(
    '/mes/dv/machinerytype',
    data,
  );

// 删除类型设置
export const deleteMachineryTypeMenu = (id: number) =>
  requestClient.delete<DVMTAPI.MachinerytypeListResp>(
    `/mes/dv/machinerytype/${id}`,
  );
